import sha1 from 'sha1'

import config from '../config/index'
import { resolve } from 'path'

import * as wechat from '../api/wechat'

import { parse as urlParse } from 'url'
import { parse as queryParse } from 'querystring'

const hear = async(ctx) => {

	const token = config.wechat.token
	const {
		signature,
		nonce,
		timestamp,
		echostr
	} = ctx.query
	const str = [token, timestamp, nonce].sort().join('')
	const sha = sha1(str)

	if(sha === signature) {
		ctx.body = echostr
	} else {
		ctx.body = 'Failed2'
	}
	//const getWechat = require('../wechat')
}

//const upload = async(ctx, next) => {
//
//	let mp = require('../wechat')
//	let client = mp.getWechat()
//
//	const data = await client.handle('uploadMaterial', 'video', resolve(__dirname, '../ice.mp4'), {
//		type: 'video',
//		description: '{"title":"haha","introduction":"heihei"}'
//	})
//
//	console.log(data)
//}

const signature = async(ctx, next) => {

	let url = ctx.query.url

	if(!url) ctx.throw(404)

	url = decodeURIComponent(url)
	let params = await wechat.getSignatureAsync(url)

	ctx.body = {
		success: true,
		params: params
	}
}

const redirect = async(ctx, next) => {

	let redirect = config.SITE_ROOT_URL + '/oauth'
	
	  let scope = 'snsapi_userinfo'
	  const { visit, id } = ctx.query
	  const params = id ? `${visit}_${id}` : visit
	
	  const url = wechat.getAuthorizeURL(scope, redirect, params)
	
	  ctx.redirect(url)
}

const oauth = async(ctx, next) => {

  const url = ctx.query.url
  const urlObj = urlParse(decodeURIComponent(url))
  const params = queryParse(urlObj.query)
  const code = params.code
  const user = await wechat.getUserByCode(code)

  console.log(user)
  ctx.session = {
    openid: user.openid
  }
  ctx.body = {
    success: true,
    user: user
  }
}



module.exports = {
	hear,

	signature,
	redirect,
	oauth
}